package com.lizicloud.user.userdelete.controller;

import com.lizicloud.application.dto.ApiResponse;
import com.lizicloud.domain.model.User;
import com.lizicloud.infrastructure.common.utils.JwtUtils;
import com.lizicloud.infrastructure.persistence.UserMapper;
import com.lizicloud.user.userdelete.dto.BatchDeleteUsersDTO;
import com.lizicloud.user.userdelete.service.UserDeleteService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * 用户删除管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@RequiredArgsConstructor
@Tag(name = "用户删除管理", description = "用户删除管理相关接口")
@SecurityRequirement(name = "Bearer Authentication")
public class UserDeleteController {
    
    private final UserDeleteService userDeleteService;
    private final JwtUtils jwtUtils;
    private final UserMapper userMapper;
    
    /**
     * 删除用户（管理员功能 - 逻辑删除）
     */
    @DeleteMapping("/{id}")
    @Operation(summary = "删除用户", description = "管理员删除指定用户（逻辑删除）")
    public ApiResponse<Void> deleteUser(
            @Parameter(description = "用户ID") @PathVariable Long id,
            HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!hasAdminRole(request)) {
                return ApiResponse.error("权限不足，需要管理员权限");
            }
            
            // 检查是否是当前登录用户
            String token = extractTokenFromRequest(request);
            String currentUseraccount = jwtUtils.getUsernameFromToken(token);
            User currentUser = userMapper.selectByUseraccount(currentUseraccount);
            
            if (currentUser != null && currentUser.getId().equals(id)) {
                return ApiResponse.error("不能删除当前登录用户");
            }
            
            return userDeleteService.logicalDeleteUser(id);
            
        } catch (Exception e) {
            log.error("删除用户失败，用户ID: {}", id, e);
            return ApiResponse.error("删除用户失败");
        }
    }
    
    /**
     * 批量删除用户（管理员功能 - 逻辑删除）
     */
    @DeleteMapping("/batch")
    @Operation(summary = "批量删除用户", description = "管理员批量删除用户（逻辑删除）")
    public ApiResponse<Void> batchDeleteUsers(
            @Valid @RequestBody BatchDeleteUsersDTO batchDeleteDTO,
            HttpServletRequest request) {
        try {
            // 验证管理员权限
            if (!hasAdminRole(request)) {
                return ApiResponse.error("权限不足，需要管理员权限");
            }
            
            // 检查是否包含当前登录用户
            String token = extractTokenFromRequest(request);
            String currentUseraccount = jwtUtils.getUsernameFromToken(token);
            User currentUser = userMapper.selectByUseraccount(currentUseraccount);
            
            if (currentUser != null && batchDeleteDTO.getUserIds().contains(currentUser.getId())) {
                return ApiResponse.error("不能删除当前登录用户");
            }
            
            return userDeleteService.batchLogicalDeleteUsers(batchDeleteDTO.getUserIds());
            
        } catch (Exception e) {
            log.error("批量删除用户失败，用户IDs: {}", batchDeleteDTO.getUserIds(), e);
            return ApiResponse.error("批量删除用户失败");
        }
    }
    
    /**
     * 从请求中提取令牌
     */
    private String extractTokenFromRequest(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return null;
    }
    
    /**
     * 检查是否为管理员角色
     */
    private boolean hasAdminRole(HttpServletRequest request) {
        try {
            String token = extractTokenFromRequest(request);
            if (token == null) {
                return false;
            }
            
            String role = jwtUtils.getRoleFromToken(token);
            return "ADMIN".equals(role);
            
        } catch (Exception e) {
            log.error("验证管理员权限失败", e);
            return false;
        }
    }
}